﻿using System.Security.Claims;
using System.Threading.Tasks;
using Caltech.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Caltech.Results;
using CaltechSoft.Service.CommandService;
using Microsoft.AspNet.Identity;
using ServiceModel = CaltechSoft.Service.DBCommand;
using AutoMapper;
using CaltechSoft.Service.ReportService;
using CaltechSoft.Service.SearchCriteria;
using CaltechSoft.Service.Repositories;
using CaltechSoft.Service.EntityFW.Entity;
using System.Linq.Expressions;
using Caltech.Extensions;
using Caltech.Service.Common;
using LinqKit;

namespace Caltech.Controllers
{
    public class POController : BaseApiController<Po, PoModels, PoSearchModel>
    {
        public UserManager<User> UserRepository { get; private set; }

        public POController(IRepository<Po> repository, UserManager<User> userRepository)
            : base(repository)
        {
            UserRepository = userRepository;
        }

        [HasAccess(Areas.POView | Areas.WOView)]
        public override IHttpActionResult Get()
        {
            var claims = ((ClaimsIdentity)User.Identity).Claims;
            var roleName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Role);
            if (roleName != null)
            {
                var queryItems = Request.RequestUri.ParseQueryString();
                string customerName = queryItems["customerName"];
                string poNumber = queryItems["poNumber"];
                string salesman = queryItems["salesman"];
                string poNo = queryItems["poNo"];
                int customerId;
                Expression<Func<Po, bool>> filter = null;

                if (int.TryParse(queryItems["customerId"], out customerId))
                {
                    filter = po => po.Company.Id == customerId;
                }
                else if (!string.IsNullOrEmpty(customerName))
                {
                    filter = po => po.Company.Name.ToLower().Contains(customerName.ToLower());
                }
                else if (!string.IsNullOrEmpty(poNumber))
                {
                    filter = po => po.PoNumber.ToLower().Contains(poNumber.ToLower());
                }

                if (roleName.Value == Roles.Salesman.ToString())
                {
                    var userId = User.Identity.GetUserId();
                    if (filter != null)
                    {
                        filter.And(po => po.CreatedBy == userId);
                    }
                    else
                    {
                        filter = po => po.CreatedBy == userId;
                    }
                }

                if (!string.IsNullOrWhiteSpace(salesman))
                {
                    var userIds = UserRepository.Users.Where(n => n.FirstName.Contains(salesman) || n.LastName.Contains(salesman)).Select(n => n.Id).ToList();
                    if (filter != null)
                    {
                        filter.And(po => userIds.Contains(po.Salesman.Id));
                    }
                    else
                    {
                        filter = po => userIds.Contains(po.Salesman.Id);
                    }
                }
                if (!string.IsNullOrWhiteSpace(poNo))
                {
                    if (filter != null)
                    {
                        filter.And(po => po.PoNumber.Contains(poNo));
                    }
                    else
                    {
                        filter = po => po.PoNumber.Contains(poNo);
                    }
                }

                return QueryData(filter);
            }
            return Ok();
        }

        [HasAccess(Areas.POView)]
        public override async Task<IHttpActionResult> GetBy(int id)
        {
            return await base.GetBy(id);
        }

        [HasAccess(Areas.POCreate)]
        public override async Task<IHttpActionResult> Post(PoModels model)
        {
            return await base.Post(model);
        }

        [HasAccess(Areas.POEdit)]
        public override async Task<IHttpActionResult> Put(PoModels model)
        {
            return await base.Put(model);
        }

        [HasAccess(Areas.PODelete)]
        public override async Task<IHttpActionResult> Delete(int id)
        {
            return await base.Delete(id);
        }
    }


}
